package is.progetto1.aritmeticExpression;

import static is.progetto1.aritmeticExpression.Utility.REGEX_VARIABLE;
import is.progetto1.exception.IllegalContextException;

public class Variable extends Expression{

	private String name=null;
	
	public Variable(String name){
		if(!name.matches(REGEX_VARIABLE))
			throw new IllegalArgumentException(name+" isn't a correct variable");
		this.name=name;
	}
	
	public Variable(String name, Expression parent){
		this(name);
		this.parent=parent;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name=name;
	}

	@Override
	public final int toAssess(Context c) throws IllegalContextException {
		Integer res=c.getVariableValue(this);
		if(res==null){
			throw new IllegalContextException("Variable "+this+" not found");
		}
		return res;
	}

	@Override
	public final String toString() {
		return this.name;
	}

	@Override
	public final int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public final boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Variable other = (Variable) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
}
